import os.path
import time

from fastapi import APIRouter

from zn.common.router.root import app
class TSettings:
    def __init__(self ):
        self.settingsFn = ""
        self.settingsInfo ={
            "server":{
                "host":"0.0.0.0" ,
                "port":2003,
                "rootPath":"/"
            },
            "components":{
                "TDB":{
                    "iot_zn_2025":{
                        "dbType":"mssql",
                        "host": "192.168.100.34",
                        "port": 1433,
                        "uid": "sa",
                        "pwd": "Hhuc1115",
                        "db": "zn-power-2025",
                        "sqlPath": "{rootPath}/datas/sqls/znpower2025"
                    },
                    "iot_zn":{
                        "dbType":"mssql",
                        "host": "192.168.100.34",
                        "port": 1433,
                        "uid": "sa",
                        "pwd": "Hhuc1115",
                        "db": "zn-power-2025",
                        "sqlPath": "{rootPath}/datas/sqls/znpower2025"
                    }
                },
                "TTerminal":{
                    "ter03":{
                        "terCode":"ter03" ,
                        "dbCode": "iot_zn_2025"
                    }
                },
                "TTer_DTUMB_Temperture":{
                    "ter03":{
                        "terCode":"ter03",
                        "dataPath":"/zndata/ter_dtu_modbus" ,
                        "dbCode": "iot_zn_2025"
                    }
                }
            }
        }

    def load(self):
        try:
            pass
        except Exception as er :
            print(er)
    @property
    def host(self):
        res = "0.0.0.0"
        try:
            if "server" in self.settingsInfo.keys():
                svrSettings = self.settingsInfo['server']
                if "host" in svrSettings:
                    res = svrSettings['host']
        except Exception as er:
            print(er)
        return  res
    @property
    def port(self):
        res = 2001
        try:
            if "server" in self.settingsInfo.keys():
                svrSettings = self.settingsInfo['server']
                if "port" in svrSettings:
                    res = svrSettings['port']
        except Exception as er:
            print(er)
        return  res
class TComponent:
    def __init__(self , _manager):
        self.manager = _manager
        self.componentCode = ""
        self.componentTypeCode = ""
    @property
    def settings(self):
        res ={}
        try:
            res = self.manager.getComponentSettings( self.componentCode)
        except Exception as er:
            self.manager.error(er)
        return res
    def start(self):
        try:
            self.stop()
            self.init()
        except Exception as er:
            self.manager.error(er)
    def init(self):
        try:
            pass
        except Exception as er:
            self.manager.error(er)
    def stop(self):
        try:
            pass
        except Exception as er:
            self.manager.error(er)
    def getStatus(self):
        res ={
            "action":"status",
            "code": self.componentCode
        }
        try:
            pass
        except Exception as er:
            self.manager.error(er)
        return res
class TComponentManager:
    def __init__(self):
        self.settings = TSettings()
        self.components = {}
        self.componentTypes = {}
    @property
    def rootPath(self):
        return  self.settings.settingsInfo['server']['rootPath']
    def error(self , err):
        print(err)
    def getComponentSettings (self , componentCode):
        res ={}
        try:
            if componentCode in self.components.keys():
                comp:TComponent = self.components[componentCode]
                compType = comp.componentTypeCode
                res = self.settings.settingsInfo['components'][compType][componentCode]
        except Exception as er :
            self.error(er)
        return res
    def registComponentType(self , typeCode , compType):
        try:
            self.componentTypes[typeCode] = compType
        except Exception as er:
            self.error(er)
    def loadComponents(self):
        try:
            for compTypeCode , comps  in self.settings.settingsInfo['components'].items():
                if compTypeCode in self.componentTypes.keys():
                    try:
                        compType = self.componentTypes[compTypeCode]
                        for compCode in comps.keys():
                            try:
                                comp = compType(self)
                                comp.componentCode = compCode
                                comp.componentTypeCode = compTypeCode
                                self.components[compCode] = comp
                                comp.start()
                            except Exception as erComp:
                                self.error(erComp)
                    except Exception as erCompType:
                        self.error(erCompType)
        except Exception as er:
            self.error(er)
    def getComponent(self , componentCode )->TComponent:
        res = None
        try:
            if componentCode in self.components.keys():
                res = self.components[componentCode]
        except Exception as er:
            self.error(er)
        return  res
    def getAbsPath(self , relatePath , autoCreate = False):
        res = ""
        try:
            targetPath = relatePath.replace("{rootPath}", self.rootPath)
            if autoCreate and (not os.path.exists(targetPath)) :
                os.makedirs(targetPath, 0x777)
            res = targetPath
        except Exception as er:
            self.error(er)
        return  res
    def action(self , componentCode , action):
        res ={}
        try:
            if componentCode in self.components.keys():
                comp = self.components[componentCode]
                if action=='start':
                    comp.start()
                    res = {"acTime": time.time()}
                elif action=='init':
                    comp.init()
                    res = {"acTime": time.time()}
                elif action=='stop':
                    comp.stop()
                    res = {"acTime": time.time()}
                elif action=='status':
                    res = comp.getStatus()
                else :
                    res ={"error":"action error!"}
            else:
                res ={"error":"componentCode is not exists!"}
        except Exception as er:
            self.error(er)
        return  res

componentManager = TComponentManager()

router = APIRouter()
@router.get("/")
async def routerGet():
    res = componentManager.settings.settingsInfo
    return res
@router.get("/{componentCode}")
async def routerGet(componentCode=""):
    res =  {"error":"componentCode is not exists"}
    if( componentCode in componentManager.settings.settingsInfo['components'].keys()):
        res = componentManager.getComponentSettings(componentCode)
    return res
app.include_router(router, prefix="/settings" ,tags=['settings'])

router = APIRouter()
@router.get("/{componentCode}/{action}")
async def routerCompAction(action:str , componentCode:str):
    res ={
        "componentCode": componentCode ,
        "action": action ,
        "result":{}
    }
    try:
        res['result'] = componentManager.action(componentCode , action)
    except Exception as er :
        componentManager.error(er)
    return res
app.include_router(router, prefix="/component" ,tags=['component'])



